/**
 * 
 */
package com.nextive.interview.dao.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * @author Martin
 *
 */
public abstract class SqLiteHelperDao {
	
	private static final String TAG = "SqlLiteUtilityDao";
	
	private SqLiteDBHelper dbHelper;
	
	private SQLiteDatabase dataBase;
	
	private Context context;
	
	public SqLiteHelperDao(Context context) {
		
		this.context = context;
		
	}
	
	protected void close() {
	
		dbHelper.close();
		
	}
	
	protected SQLiteDatabase getDatabase() {
		
		if (dbHelper == null)
			dbHelper = new SqLiteDBHelper(context);
		
		return dbHelper.getWritableDatabase();
		
	}
	
//	private void open() {
//		
//		dbHelper = new SqLiteDBHelper(context);
//		dataBase = dbHelper.getWritableDatabase();
//		
//	}

	protected abstract String getDBName();
	
	protected abstract int getDBVersion();
	
	protected abstract String getDBCreateStatement();
	
	protected abstract String getDBDropStatement();
	
	private class SqLiteDBHelper extends SQLiteOpenHelper {

    	SqLiteDBHelper(Context context) {
    		
            super(context, getDBName(), null, getDBVersion());
            
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(getDBCreateStatement());
            
        }

		@Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        	
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL(getDBDropStatement());
            onCreate(db);
            
        }
    }


}
